//
//  EmoticonView.swift
//  02-表情键盘
//
//  Created by  NorthCity on 15/11/12.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
private let emoticonCellID = "emoticonCellID"
class EmoticonView: UIView {
/// 选中表情回调函数
    private var selectedEmoticonCallBack:(emoticon:Emoticon)->()

    init(selectedEmoticon:(emoticon:Emoticon)->()) {
        self.selectedEmoticonCallBack = selectedEmoticon
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 216
        super.init(frame: rect)
        setUpUI()
//        跳到默认分组
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
           self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - 懒加载控件
    private lazy var packages = EmoticonManager.sharedManager.packages
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonViewLayout())
    private lazy var toolBar = UIToolbar()
    private class EmoticonViewLayout:UICollectionViewFlowLayout{
        override func prepareLayout() {
            super.prepareLayout()
            let col:CGFloat = 7
            let row:CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            let margin = (collectionView!.bounds.height - w * row)*0.5
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
        }
    }
    
//    MARK: - 监听函数
  @objc private func clickItem(item:UIBarButtonItem){
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

}

extension EmoticonView{
//    设置 UI 
    func setUpUI(){
//    0 背景颜色
        backgroundColor = UIColor.whiteColor()
//    1 添加控件
        addSubview(collectionView)
        addSubview(toolBar)
//    2 自动布局
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolBar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }

            toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(36)
        }
//     3 准备控件
        prepareToolBar()
        prepareCollectionView()
             }
    
//  MARK: -  准备工具栏
    func prepareToolBar(){
        tintColor = UIColor.grayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        for i in packages{
            let item = UIBarButtonItem(title: i.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:")
        
            items.append(item)
            item.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
    }
//    MARK: - 准备 collectionView
    func prepareCollectionView(){
        collectionView.backgroundColor = UIColor.lightGrayColor()
        
//       注册 cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: emoticonCellID)
//       数据源方法
        collectionView.dataSource = self
//        代理方法
        collectionView.delegate = self
        
    }
    
}

//    MARK: - 数据源方法实现
extension EmoticonView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(packages[section].emoticons.count)
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCellID, forIndexPath: indexPath) as! EmoticonViewCell
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let em = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(emoticon: em)
    }
    
}
//MARK: - 自定义 cell
private class EmoticonViewCell:UICollectionViewCell{
//    表情符号
    var emoticon:Emoticon?{
        didSet{
          emoticonButton.setImage(UIImage(contentsOfFile: (emoticon?.imagePath)!), forState: UIControlState.Normal)
            
//            这里注意 cell 重用问题, 可选属性,一般判定不为空才执行操作,但是这里因为是 button imgage 和 title ,所以不能判定
          emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
          emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            // 是否删除按钮
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
//    栏加载控件
private lazy var emoticonButton:UIButton = UIButton()
    
}





